const jwt = require("jsonwebtoken");

exports.sign = function (confSymbol) {
	/**
	 * 签名
	 *
	 * @param {Hash} payload 载荷
	 *
	 * @return {Promise}
	 */
	return function (payload) {
		let conf = this[confSymbol];

		let curPayload = payload ? Object.assign(conf.payload, payload) : conf.payload;

		return new Promise((resolve, reject) => {
			jwt.sign(
				curPayload,
				conf.secretOrPrivateKey,
				{
					algorithm: conf.alg
				},
				(err, token) => (err ? reject(err) : resolve(token))
			);
		});
	};
};

exports.verify = function (confSymbol) {
	/**
	 * 签证签名
	 *
	 * @param {String} token 待验证的签名字符串
	 *
	 * @return {Promise}
	 */
	return function (token) {
		let conf = this[confSymbol];

		return new Promise((resolve, reject) => {
			jwt.verify(
				token,
				conf.secretOrPublichKey,
				{
					algorithms: [conf.alg]
				},
				(err, payload) => (err ? reject(err) : resolve(payload))
			);
		});
	};
};
